﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PeaceBlog
{
    public static class HtmlHelpers
    {
        private class ScriptBlock : IDisposable
        {
            private const string scriptsKey = "scripts";
            public static List<string> pageScripts
            {
                get
                {
                    if (HttpContext.Current.Items[scriptsKey] == null)
                        HttpContext.Current.Items[scriptsKey] = new List<string>();
                    return (List<string>)HttpContext.Current.Items[scriptsKey];
                }
            }

            WebViewPage webPageBase;

            public ScriptBlock(WebViewPage webPageBase)
            {
                this.webPageBase = webPageBase;
                this.webPageBase.OutputStack.Push(new StringWriter());
            }

            public void Dispose()
            {
                pageScripts.Add(((StringWriter)this.webPageBase.OutputStack.Pop()).ToString());
            }
        }

        public static IDisposable BeginScripts(this HtmlHelper helper)
        {
            return new ScriptBlock((WebViewPage)helper.ViewDataContainer);
        }

        public static MvcHtmlString PageScripts(this HtmlHelper helper)
        {
            return MvcHtmlString.Create(string.Join(Environment.NewLine, ScriptBlock.pageScripts.Select(s => s.ToString())));
        }

        public static MvcHtmlString ValidationSummaryEx(this HtmlHelper helper, string mesaj = "", MessageType type = MessageType.Success)
        {
            try
            {
                string baseMsg = "<div class='alert alert-{0}'>{1}</div>";
                if (helper.ViewData.ModelState.Keys.Contains("Başarılı"))
                {
                    return new System.Web.Mvc.MvcHtmlString(String.Format(baseMsg, type.GetStringValue(), helper.ViewData.ModelState[type.GetStringValue()].Errors.First().ErrorMessage));
                }
                else if (!string.IsNullOrEmpty(mesaj) && !string.IsNullOrEmpty(type.GetStringValue()))
                {
                    return new System.Web.Mvc.MvcHtmlString(String.Format(baseMsg, type.GetStringValue(), mesaj));
                }
            }
            catch { }
            return new System.Web.Mvc.MvcHtmlString("");
        }

        public static MvcHtmlString LabelMessage(this HtmlHelper helper, string mesaj, LabelMessageType type)
        {
            string baseMsg = "<span class='label label-{0}'>{1}</span>";
            return new MvcHtmlString(
                String.Format(baseMsg, type.GetStringValue(), mesaj)
                );
        }

        public static MvcHtmlString PageTitle(this HtmlHelper helper, string title)
        {
            return new MvcHtmlString(String.Format("<h3 class='page-title'>{0}</h3>", title));
        }
    }
}